# 导入必要的包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


class RadarChart:
    """雷达图绘制系统"""

    def __init__(self, data_file=None, figsize=(10, 8)):
        """
        初始化雷达图绘制系统
        参数:
            data_file: 数据文件路径，如果提供则自动加载
            figsize: 图表大小
        """
        self.data = None
        self.fig = None
        self.ax = None
        self.figsize = figsize

        print("初始化雷达图绘制系统")
        if data_file:
            self.load_data(data_file)
            print(f"数据文件: {data_file}")

    def load_data(self, file_path=None):
        """加载数据"""
        try:
            if file_path:
                self.data = pd.read_csv(file_path)
                print(f"成功加载数据，共 {len(self.data)} 条记录")
            else:
                raise ValueError("未提供数据文件路径")
        except Exception as e:
            print(f"加载数据出错: {e}")
            print("使用生成的示例数据代替")
            self._generate_example_data()

        return self.data

    def _generate_example_data(self):
        """生成示例数据（内部方法）"""
        regions = ['Region1', 'Region2', 'Region3', 'Region4', 'Region5']
        historical_dew_point = np.random.normal(loc=10, scale=3, size=len(regions))
        predicted_dew_point = np.random.normal(loc=12, scale=3, size=len(regions))

        self.data = pd.DataFrame({
            'region': regions,
            'historical_dew_point': historical_dew_point,
            'predicted_dew_point': predicted_dew_point
        })
        print("已生成示例数据")

    def plot_radar(self, region_col='region', hist_col='historical_dew_point',
                   pred_col='predicted_dew_point', title='区域露点温度比较'):
        """
        绘制雷达图

        参数:
            region_col: 区域名称列
            hist_col: 历史数据列
            pred_col: 预测数据列
            title: 图表标题
        """
        # 确保数据已加载
        if self.data is None:
            self._generate_example_data()

        # 提取数据
        regions = self.data[region_col].tolist()
        hist_values = self.data[hist_col].tolist()
        pred_values = self.data[pred_col].tolist()

        # 计算角度 - 确保数量正确
        N = len(regions)
        theta = np.linspace(0, 2 * np.pi, N, endpoint=False)

        # 创建极坐标图
        self.fig = plt.figure(figsize=self.figsize)
        self.ax = plt.subplot(111, projection='polar')

        # 绘制雷达图 - 闭合数据
        theta_closed = np.append(theta, theta[0])
        hist_closed = np.append(hist_values, hist_values[0])
        pred_closed = np.append(pred_values, pred_values[0])

        # 绘制历史数据
        self.ax.plot(theta_closed, hist_closed, 'o-', linewidth=2, label='历史数据')
        self.ax.fill(theta_closed, hist_closed, alpha=0.25)

        # 绘制预测数据
        self.ax.plot(theta_closed, pred_closed, 'o-', linewidth=2, label='预测数据')
        self.ax.fill(theta_closed, pred_closed, alpha=0.25)

        # 设置角度刻度标签 - 正确设置刻度和标签
        self.ax.set_xticks(theta)
        self.ax.set_xticklabels(regions)

        # 设置径向网格线
        self.ax.set_rgrids([2, 4, 6, 8, 10, 12, 14, 16], angle=0)

        # 设置标题
        self.ax.set_title(title, fontsize=15, pad=20)

        # 添加图例
        self.ax.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1))

        return self.fig, self.ax

    def add_statistics(self):
        """添加统计信息到图表"""
        if self.fig is None or self.data is None:
            print("没有图表或数据可用")
            return

        # 计算基本统计量
        hist_mean = self.data['historical_dew_point'].mean()
        pred_mean = self.data['predicted_dew_point'].mean()
        diff_mean = pred_mean - hist_mean
        diff_pct = (diff_mean / hist_mean) * 100 if hist_mean != 0 else 0

        stats_text = f"历史平均: {hist_mean:.2f}°C\n"
        stats_text += f"预测平均: {pred_mean:.2f}°C\n"
        stats_text += f"变化量: {diff_mean:+.2f}°C\n"
        stats_text += f"变化率: {diff_pct:+.1f}%"

        # 添加统计信息文本框
        plt.figtext(0.85, 0.15, stats_text, ha='center',
                    bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

    def save_chart(self, filename=None):
        """保存图表"""
        if self.fig is None:
            print("没有可保存的图表")
            return

        if filename is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f'radar_chart_{timestamp}.png'

        self.fig.savefig(filename, dpi=300, bbox_inches='tight')
        print(f"图表已保存到 {filename}")

    def show_chart(self):
        """显示图表"""
        if self.fig is None:
            print("没有可显示的图表")
            return

        plt.tight_layout()
        plt.show()

    def run(self, data_file=None, region_col='region', hist_col='historical_dew_point',
            pred_col='predicted_dew_point', title='区域露点温度比较'):
        """运行完整的雷达图绘制流程"""
        # 加载数据
        if data_file:
            self.load_data(data_file)
        elif self.data is None:
            self._generate_example_data()

        # 绘制雷达图
        self.plot_radar(region_col, hist_col, pred_col, title)

        # 添加统计信息
        self.add_statistics()

        # 保存和显示
        self.save_chart()
        self.show_chart()


# 主函数示例
if __name__ == "__main__":
    # 创建雷达图对象
    radar = RadarChart()

    # 方法1: 使用run方法一步完成
    radar.run(title='常州市各区域露点温度比较')